<template>
  <div style="margin: 20px;">
    <el-row>
      <el-col :span="2">
        <el-input
          placeholder="请输入订单编号"
          v-model="SelectCommodityForm.commodityId"
          style="width: 150px; margin-right: 10px;"
          @change="selsectcommodityId"
        />
      </el-col>

      <el-col :push="2" :span="2">
        <el-select
          v-model="SelectCommodityForm.paymentStatus"
          placeholder="请选择支付状态"
          style="width: 150px"
          @change="selsectpaymentStatus"
        >
          <el-option
            v-for="item in cities"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-col>

      <el-col :push="4" :span="2">
        <el-select
          v-model="SelectCommodityForm.shippingStatus"
          placeholder="请选择发货状态"
          style="width: 150px"
          @change="selsectpaymentStatus"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-col>
    </el-row>

    <el-row style="margin-top: 10px;">
      <el-col :push="22" :span="2">
        <el-dropdown trigger="click">
          <span class="el-dropdown-link">
            待处理业务
            <el-icon class="el-icon--right"><caret-bottom /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item class="clearfix" @click="ccc" type="warning">
                待签收
                <el-badge class="mark" :value="shopToBeSignedForTotal" />
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-col>
    </el-row>

    <div v-for="(order, index) in orderData" :key="index" style="margin-top: 20px;">
      <el-descriptions :title="`订单 ${index + 1} 信息`" :column="2" border>
        <el-descriptions-item label="订单编号">{{ order.commodityId }}</el-descriptions-item>
        <el-descriptions-item label="下单时间">{{ formatDate(order.createdAt) }}</el-descriptions-item>
        <el-descriptions-item label="收货人">{{ order.receiverName }} ({{ order.receiverPhone }})</el-descriptions-item>
        <el-descriptions-item label="地址">{{ order.addressInfo }}</el-descriptions-item>
        <el-descriptions-item label="支付状态">{{ paymentStatusText(order.paymentStatus) }}</el-descriptions-item>
        <el-descriptions-item label="发货状态">{{ shippingStatusText(order.shippingStatus) }}</el-descriptions-item>
        <el-descriptions-item label="退款状态" v-if="order.refund != 0">{{ refundText(order.refund) }}</el-descriptions-item>
      </el-descriptions>

      <el-table :data="order.commodityDetails || []" style="width: 100%; margin-top: 20px;" stripe>
        <el-table-column prop="productName" label="商品名称"></el-table-column>
        <el-table-column prop="price" label="单价" width="180">
          <template #default="scope">￥{{ scope.row.price }}</template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" width="180"></el-table-column>
        <el-table-column label="总价" width="180">
          <template #default="scope">￥{{ scope.row.totalPrice }}</template>
        </el-table-column>
        <el-table-column prop="notes" label="备注"></el-table-column>
      </el-table>

      <div class="order-total" style="text-align: right; margin-top: 20px;">
        <el-row>
          <el-col :span="4">
            <span>订单总金额：￥{{ order.total }}</span>
          </el-col>
          <el-col :push="14" :span="4">
            <span>折扣后价格：￥{{ order.discountedPrices }}</span>
          </el-col>
        </el-row>
      </div>
      <hr />
    </div>

    <el-dialog v-model="isShow3" title="退款订单处理" width="500">
      <span>
        <p>待签收订单处理</p>
        <p>当前有：{{ shopToBeSignedForTotal }}条待签收订单</p>
        <p>是否前往处理待签收订单？</p>
      </span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isShow3 = false">取消</el-button>
          <el-button @click="handle">确认前往</el-button>
        </div>
      </template>
    </el-dialog>

    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="SelectCommodityForm.pageNum"
        v-model:page-size="SelectCommodityForm.pageSize"
        :page-sizes="[1, 4, 6, 8]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
export default {
  name: 'OrderDetail',
  data() {
    return {
      orderData: [],
      SelectCommodityForm: {
        pageNum: 1,
        pageSize: 10,
        commodityId: null,
        paymentStatus: null,
        shippingStatus: null,
      },
      total: 0,
      shopToBeSignedForList: [],
      shopToBeSignedForTotal: 0,
      isShow3: false,
      intervalId: null,
      cities: [
        { label: '未支付', value: '0' },
        { label: '已支付', value: '1' },
        { label: '全部', value: null },
      ],
      options: [
        { label: '全部', value: null },
        { label: '未发货', value: '0' },
        { label: '已发货', value: '1' },
        { label: '已签收', value: '2' },
        { label: '退货中', value: '3' },
        { label: '已退货', value: '4' },
      ],
    };
  },
  methods: {
    selsectSignForReceipts() {
      this.$http.post('/order/commodity/shopToBeSignedFor', this.ShopToBeSignedForForm)
        .then(resp => {
          this.shopToBeSignedForList = resp.data.data.list;
          this.shopToBeSignedForTotal = resp.data.data.total;
          if (this.shopToBeSignedForTotal > 0) {
            this.isShow3 = true;
          } else {
            this.$message.error('没有待签收订单');
          }
        })
        .catch(error => {
          this.$message.error('请求待签收订单失败，请重试。');
          console.error(error);
        });
    },
    
    selsectpaymentStatus() {
      this.selsectcommodity();
    },

    ccc() {
      this.$router.push("/shopreceiptofgoods");
    },
    
    selsectcommodityId() {
      if (!this.SelectCommodityForm.commodityId) {
        this.$message.warning("请输入订单编号");
        return;
      }
      this.selsectcommodity();
    },

    handle() {
      this.$router.push("/shopreceiptofgoods");
    },

    handleSizeChange(val) {
      this.SelectCommodityForm.pageSize = val;
      this.selsectcommodity();
    },

    handleCurrentChange(val) {
      this.SelectCommodityForm.pageNum = val;
      this.selsectcommodity();
    },

    selsectcommodity() {
      this.$http.post('/order/commodity/selsectcommodityshop', this.SelectCommodityForm)
        .then(resp => {
          this.orderData = resp.data.data.list;
          this.orderData.sort((a, b) => b.paymentStatus - a.paymentStatus);
          this.total = resp.data.data.total;
        })
        .catch(error => {
          this.$message.error('请求失败，请重试。');
          console.error(error);
        });
    },

    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
    },

    refundText(status) {
      const statusMap = {
        0: '未申请退款',
        1: '待处理',
        2: '已同意',
        3: '已拒绝',
      };
      return statusMap[status] || '未知状态';
    },

    paymentStatusText(status) {
      return status === 1 ? '已支付' : '未支付';
    },

    shippingStatusText(status) {
      const statusMap = ['未发货', '已发货', '已签收', '退货中', '已退货'];
      return statusMap[status] || '未知状态';
    },

    startPolling() {
      this.intervalId = setInterval(() => {
        this.selsectcommodity();
        this.selsectSignForReceipts();
      }, 60000); // 每60秒轮询
    },

    stopPolling() {
      clearInterval(this.intervalId);
    },
  },
  mounted() {
    this.selsectcommodity();
    this.selsectSignForReceipts();
    this.startPolling();
  },
  beforeUnmount() {
    this.stopPolling();
  },
};
</script>

<style scoped>
/* 样式可以根据需要调整 */
.el-dropdown-link {
  color: #5DE2E7; /* 改变为你想要的颜色 */
}
</style>